package 尚硅谷.juc.test16;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 资源类
 */
public class ShareData {

    /**
     * number起到标志位得作用
     * 当number=1，则A线程打印5次
     * 当number=2，则B线程打印10次
     * 当number=3，则C线程打印15次
     * 这样循环10次
     */
    private int number=1;
    private Lock lock=new ReentrantLock();
    private Condition condition1=lock.newCondition();
    private Condition condition2=lock.newCondition();
    private Condition condition3=lock.newCondition();

    public void print5(){
        try{

            lock.lock();
            //1：判断
            //while循环判断，防止虚假唤醒
            while (number!=1){
                condition1.await();
            }
            //2：干活
            for (int i=1;i<=5;i++){
                System.out.println(Thread.currentThread().getName()+"\t"+5);
            }
            //3：通知
            number=2;//修改标致位
            /**
             * 精确唤醒线程
             */
            condition2.signal();//通知第二个
        }catch (Exception exception){

        }finally {
            lock.unlock();
        }

    }

    public void print10(){
        try{

            lock.lock();
            //1：判断
            //while循环判断，防止虚假唤醒
            while (number!=2){
                condition1.await();
            }
            //2：干活
            for (int i=1;i<=10;i++){
                System.out.println(Thread.currentThread().getName()+"\t"+10);
            }
            //3：通知
            number=3;//修改标致位
            /**
             * 精确唤醒线程
             */
            condition3.signal();//通知第三个
        }catch (Exception exception){

        }finally {
            lock.unlock();
        }

    }

    public void print15(){
        try{

            lock.lock();
            //1：判断
            //while循环判断，防止虚假唤醒
            while (number!=3){
                condition1.await();
            }
            //2：干活
            for (int i=1;i<=15;i++){
                System.out.println(Thread.currentThread().getName()+"\t"+15);
            }
            //3：通知
            number=1;//修改标致位
            /**
             * 精确唤醒线程
             */
            condition1.signal();//通知第二个
        }catch (Exception exception){

        }finally {
            lock.unlock();
        }

    }

}
